<template>
  <div class="service-detail-view">
    <div class="page-header">
      <div class="header-title">
        <el-button @click="goBack" type="text" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
        <h1>{{ serviceDetail?.service?.serviceName ? serviceDetail.service.serviceName + ' 详细信息' : '加载中...' }}</h1>
        <p class="subtitle">查看服务项目的详细进度和负责经理情况</p>
      </div>
    </div>

    <div v-if="loading" v-loading="loading" class="loading-container">
      <div class="loading-text">正在加载服务项目详情...</div>
    </div>

    <template v-else-if="serviceDetail">
      <!-- 服务项目基本信息卡片 -->
      <div class="overview-cards">
        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon><Setting /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ serviceDetail.service.totalTasks }}</div>
              <div class="stat-label">分配任务数</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon progress">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ serviceDetail.service.completedTasks }}</div>
              <div class="stat-label">已完成任务</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon completion">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ serviceDetail.service.progressPercentage }}%</div>
              <div class="stat-label">完成进度</div>
            </div>
          </div>
        </el-card>

        <el-card class="overview-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon delayed">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ serviceDetail?.service?.completionCycle ? getCompletionCycleText(serviceDetail.service.completionCycle) : '加载中...' }}</div>
              <div class="stat-label">完成周期</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 服务项目详细信息 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><Setting /></el-icon>
              服务项目信息
            </h2>
            <p class="section-desc">该服务项目的基本配置和设置</p>
          </div>
        </template>
        
        <div class="service-info-grid">
          <div class="info-item">
            <label>服务名称:</label>
            <span>{{ serviceDetail.service.serviceName }}</span>
          </div>
          <div class="info-item">
            <label>服务类型:</label>
            <span>{{ serviceDetail.service.serviceType }}</span>
          </div>
          <div class="info-item">
            <label>完成周期:</label>
            <span>{{ serviceDetail?.service?.completionCycle ? getCompletionCycleText(serviceDetail.service.completionCycle) : '加载中...' }}</span>
          </div>
          <div class="info-item">
            <label>周期值:</label>
            <span>{{ serviceDetail.service.cycleValue }}</span>
          </div>
          <div class="info-item">
            <label>开始日期:</label>
            <span>{{ serviceDetail.service.startDate || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>结束日期:</label>
            <span>{{ serviceDetail.service.endDate || '未设置' }}</span>
          </div>
          <div class="info-item">
            <label>提醒频率:</label>
            <span>{{ serviceDetail.service.reminderFrequency || '未设置' }}</span>
          </div>
          <div class="info-item full-width">
            <label>提醒内容:</label>
            <span>{{ serviceDetail.service.reminderContent || '未设置' }}</span>
          </div>
        </div>
      </el-card>

      <!-- 各客户经理完成情况 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              各客户经理完成情况
            </h2>
            <p class="section-desc">该服务项目在各个客户经理处的完成进度</p>
          </div>
        </template>
        
        <el-table 
          :data="serviceDetail.managerStats" 
          style="width: 100%"
          v-loading="loading"
          empty-text="暂无客户经理数据"
        >
          <el-table-column prop="managerName" label="客户经理" width="150">
            <template #default="scope">
              <div class="manager-info">
                <el-avatar :size="32" class="manager-avatar">
                  {{ scope.row.managerName.charAt(0) }}
                </el-avatar>
                <div class="manager-name-container">
                  <span class="manager-name">{{ scope.row.managerName }}</span>
                  <el-icon 
                    v-if="serviceDetail?.managerStats && isInBottomTenPercent(serviceDetail.managerStats)(scope.row)" 
                    class="warning-indicator"
                    color="#f56c6c"
                    size="14"
                  >
                    <Warning />
                  </el-icon>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalTasks" label="总任务数" width="100" align="center" />
          <el-table-column prop="completedTasks" label="已完成" width="100" align="center" />
          <el-table-column prop="completionRate" label="完成率" width="200" align="center">
            <template #default="scope">
              <div class="completion-rate-cell">
                <el-progress 
                  :percentage="scope.row.completionRate" 
                  :status="scope.row.completionRate < 30 ? 'exception' : scope.row.completionRate < 70 ? 'warning' : 'success'"
                  :stroke-width="8"
                />
                <span class="completion-rate-text">{{ scope.row.completionRate }}%</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分配客户列表 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><User /></el-icon>
              分配客户列表
            </h2>
            <p class="section-desc">该服务项目分配的所有客户信息</p>
          </div>
        </template>
        
        <el-table 
          :data="serviceDetail.assignedClients" 
          style="width: 100%"
          empty-text="暂无客户数据"
        >
          <el-table-column prop="clientCode" label="客户代码" width="120" />
          <el-table-column prop="clientName" label="客户名称" width="200" />
          <el-table-column prop="marketType" label="市场类型" width="100" align="center" />
          <el-table-column prop="terminalType" label="终端类型" width="150" align="center" />
        </el-table>
      </el-card>

      <!-- 最近工作日志 -->
      <el-card class="section-card" shadow="never">
        <template #header>
          <div class="section-header">
            <h2>
              <el-icon class="header-icon"><List /></el-icon>
              最近工作日志
            </h2>
            <p class="section-desc">该服务项目的最近完成记录</p>
          </div>
        </template>
        
        <el-table 
          :data="serviceDetail.recentWorkLogs" 
          style="width: 100%"
          empty-text="暂无工作日志"
        >
          <el-table-column prop="clientName" label="客户名称" width="150" />
          <el-table-column prop="clientCode" label="客户代码" width="120" />
          <el-table-column prop="managerName" label="客户经理" width="120" />
          <el-table-column prop="completionDate" label="完成日期" width="120" align="center" />
          <el-table-column prop="notes" label="备注" />
          <el-table-column prop="createdAt" label="创建时间" width="120" align="center" />
        </el-table>
      </el-card>
    </template>

    <div v-else class="error-container">
      <el-empty description="未找到服务项目信息或该服务项目已被删除" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  Setting,
  Clock,
  CircleCheck,
  List,
  Trophy,
  User,
  Warning
} from '@element-plus/icons-vue';
import { trpc } from '../../utils/trpc';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const serviceDetail = ref(null);

const serviceId = Number(route.params.id);

// 转换完成周期为中文显示
const getCompletionCycleText = (cycle: string) => {
  const cycleMap = {
    'daily': '每日',
    'weekly': '每周', 
    'monthly': '每月',
    'quarterly': '每季度',
    'yearly': '每年'
  };
  return cycleMap[cycle] || cycle;
};

// 计算后10%的客户经理（用于警示标识）
const isInBottomTenPercent = computed(() => (managerStats: any[]) => {
  if (!managerStats || managerStats.length === 0) return () => false;
  
  // 按完成率排序
  const sortedStats = [...managerStats].sort((a, b) => a.completionRate - b.completionRate);
  
  // 计算后10%的数量，至少为1个
  const bottomTenPercentCount = Math.max(1, Math.ceil(sortedStats.length * 0.1));
  
  // 获取后10%的完成率阈值
  const threshold = sortedStats[bottomTenPercentCount - 1]?.completionRate || 0;
  
  return (manager: any) => manager.completionRate <= threshold;
});

// 返回按钮逻辑
const goBack = () => {
  router.push('/service-details');
};

// 加载服务项目详情数据
const loadServiceDetail = async () => {
  if (!serviceId || isNaN(serviceId)) {
    ElMessage.error('无效的服务项目ID');
    router.push('/service-details');
    return;
  }

  loading.value = true;
  try {
    console.log('开始加载服务项目详情，ID:', serviceId);
    const result = await trpc.stats.serviceDetail.query({ serviceId });

    console.log('服务项目详情API返回结果:', result);

    if (result.success && result.data) {
      serviceDetail.value = result.data;
      console.log('服务项目详情加载成功:', result.data);
    } else {
      console.error('获取服务项目详情失败:', result.message);
      ElMessage.error(result.message || '获取服务项目详情失败');
    }
  } catch (error) {
    console.error('加载服务项目详情失败:', error);
    ElMessage.error('加载数据失败，请检查网络连接');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadServiceDetail();
});
</script>

<style scoped>
.service-detail-view {
  max-width: 1400px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 32px;
}

.header-title h1 {
  margin: 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #262626;
}

.back-btn {
  font-size: 14px;
  padding: 0;
  margin-bottom: 8px;
  color: #1890ff;
}

.back-btn:hover {
  color: #40a9ff;
}

.subtitle {
  margin: 0;
  color: #8c8c8c;
  font-size: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.loading-text {
  font-size: 16px;
  color: #8c8c8c;
}

.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 24px;
  margin-bottom: 32px;
}

.overview-card {
  border-radius: 12px;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.progress {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.delayed {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-icon.completion {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  color: #262626;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #8c8c8c;
}

.section-card {
  margin-bottom: 32px;
  border-radius: 12px;
}

.section-header h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
}

.section-desc {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.service-info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: 600;
  color: #262626;
  min-width: 80px;
}

.info-item span {
  color: #8c8c8c;
}

.manager-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.manager-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.manager-name-container {
  display: flex;
  align-items: center;
  gap: 6px;
}

.manager-name {
  font-weight: 500;
}

.warning-indicator {
  flex-shrink: 0;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
}

.completion-rate-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.completion-rate-cell .el-progress {
  flex: 1;
  min-width: 120px;
}

.completion-rate-text {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  min-width: 40px;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .service-detail-view {
    padding: 16px;
  }
  
  .overview-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .service-info-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-number {
    font-size: 24px;
  }
}
</style>